import random
import string
import yaml
import re
import datetime
from string import Template
def generate_token(length=16):
    """生成指定长度的随机字符串（字母 + 数字）"""
    characters = string.ascii_letters + string.digits  # a-z, A-Z, 0-9
    return ''.join(random.choices(characters, k=length))

# 示例：生成 16 位 token
# token = generate_token()
# print(token)

mock_login_token = generate_token()
print(f'这次返回的token是{mock_login_token}')
token4 = mock_login_token

def string_replace(source_data:dict,dict1:dict = {},**kwargs) -> dict:
    data_str = yaml.safe_dump(source_data)
    print('-----替换前的模版-------')
    print(data_str)

    t = Template(data_str)
    if dict1 == {}:
        new_data = t.substitute(**kwargs)
    elif kwargs == {}:
        new_data = t.substitute(dict1)
      
    print('-----替换后的实际数据-------')
    print(new_data)

    #返回一个对象
    return yaml.safe_load(new_data)


class Utill:

    @classmethod
    def replace(cls,name:str):
        return eval(name)
    
    @classmethod
    def date(cls):
        return datetime.datetime.now().strftime('%Y:%m:%d %H:%M:%S')
    
    @classmethod
    def pinjie(cls,*args):
        str1 = ''
        for i in args:
            str1 = i + str1
        
        return str1

def re_sub_fuc(match):
    
    #下面两种写法都可以
    # sub,fuc_name,param = match.group(0),match.group(1),match.group(2)
    sub,fuc_name,param = match[0],match[1],match[2]
    print(sub,fuc_name,param)
    u = Utill()
    if not param:
        res = getattr(u,fuc_name)()
    else:
        param_list = param.split(',')
        res = getattr(u,fuc_name)(*param_list)

    return res

PATH1 = r'/Users/show/PythonAndQA(code)/python-study2025/8_anything/5example.yaml'
with open(PATH1,encoding='utf8') as f:
    lists = yaml.safe_load(f)
    i = lists[0]
    print(i)
    # target = i['request']['token']
    # print(target)
    # print(eval(target))

    #替换
    # str1 = str(i)
    # str2 = str1.replace("'$", '').replace("$'", '')
    # print(str2)
    # print(eval(str2))
    
    print('********************************')
    # s = string_replace(i,mock_login_token=mock_login_token)
    # print(s)
    s = string_replace(i,{'mock_login_token':mock_login_token})
    print(s)

    print("-------------------分割-------------------")

    j = lists[1]

    str_j = yaml.safe_dump(j)
    reexp = "\$\{(.*?)\((.*?)\)\}"
    #findall 方法返回的是一个list ,并且会按照分组来展示
    l = re.findall(reexp,str_j)
    print(l)
    new_str = re.sub(reexp,re_sub_fuc,str_j)
    print(new_str)
